using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;

namespace ShareTools.WorkflowManager
{
    public partial class ListBasedWorkflowManager : Form
    {
        public ListBasedWorkflowManager()
        {
            InitializeComponent();
        }

        private void WorkflowManager_Load(object sender, EventArgs e)
        {

        }

        public void GetAllLists()
        {
            rchTxtOuput.Text = "";
            StringBuilder sb = new StringBuilder();
            try
            {                
                using (SPSite spSite = new SPSite(txtSiteUrl.Text))
                {
                    using (SPWeb spWeb = spSite.RootWeb)
                    {
                        chxlbLists.Items.Clear();
                        foreach (SPList listItem in spWeb.Lists)
                        {
                            chxlbLists.Items.Add(listItem.Title, true);
                        }
                        chxSelectAll.Checked = true;
                    }
                }
            }
            catch (Exception ex)
            {
                sb.Append("Request - Failed.\n");
                sb.Append("Error occured while fetching all list for site.\n");
                sb.Append("Please, check the site URL.\n\n");
                sb.Append("Exception Details:\n\n" + ex.ToString());                
                rchTxtOuput.Text = sb.ToString();
            }
        }

        public void GetAllWorkflows()
        {
            rchTxtOuput.Text = "";
            StringBuilder sb = new StringBuilder();
            try
            {
                using (SPSite spSite = new SPSite(txtSiteUrl.Text))
                {
                    using (SPWeb spWeb = spSite.RootWeb)
                    {
                        cmbWorkflow.Items.Clear();
                        cmbWorkflow.Items.Add("Select...");
                        foreach (SPWorkflowTemplate wftempalte in spWeb.WorkflowTemplates)
                        {
                            cmbWorkflow.Items.Add(wftempalte.Name);
                        }
                    }
                }
                cmbWorkflow.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                sb.Append("Request - Failed.\n");
                sb.Append("Error occured while fetching all workflows for site.\n");
                sb.Append("Please, check the site URL.\n\n");
                sb.Append("Exception Details:\n\n" + ex.ToString());
                rchTxtOuput.Text = sb.ToString();
            }
        }

        private void btnFetchData_Click(object sender, EventArgs e)
        {
            GetAllLists();
            GetAllWorkflows();
        }

        private void chxSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            bool isSelect = chxSelectAll.Checked;
            for (int i = 0; i < chxlbLists.Items.Count; i++)
                chxlbLists.SetItemChecked(i, isSelect);
        }

        private void btnAttachWorkflow_Click(object sender, EventArgs e)
        {
            rchTxtOuput.Text = "";
            if (cmbWorkflow.SelectedItem.ToString().Equals("Select...") || string.IsNullOrEmpty(txtAssocName.Text))
            {
                MessageBox.Show("Please make sure workflow is selected and the association name is provided");
                return;
            }
            System.Globalization.CultureInfo _cultureInfo = System.Globalization.CultureInfo.CurrentCulture;
            SPWorkflowTemplate _wft;
            SPList _ssrList = null;
            SPList _taskList;
            SPList _wfHistoryList;
            SPWorkflowAssociation _newAsso;
            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            using (SPSite spSite = new SPSite(txtSiteUrl.Text))
            {
                spSite.AllowUnsafeUpdates = true;
                using (SPWeb spWeb = spSite.RootWeb)
                {
                    spWeb.AllowUnsafeUpdates = true;
                    foreach (object item in chxlbLists.CheckedItems)
                    {
                        try
                        {
                            //cmbWorkflow.Items.Add(item.ToString());
                            _ssrList = spWeb.Lists[item.ToString()];
                            _wft = spWeb.WorkflowTemplates.GetTemplateByName(cmbWorkflow.SelectedItem.ToString(), _cultureInfo);
                            _taskList = spWeb.Lists["Tasks"];
                            _wfHistoryList = spWeb.Lists["Workflow History"];

                            _newAsso = null;
                            _newAsso = SPWorkflowAssociation.CreateListAssociation(_wft, txtAssocName.Text, _taskList, _wfHistoryList);
                            _newAsso.AutoStartCreate = true;
                            _ssrList.AddWorkflowAssociation(_newAsso);
                            _ssrList.Update();
                            sb.Append("List: " + _ssrList.Title + " - Success\n");
                        }
                        catch (Exception ex)
                        {
                            if (_ssrList == null) MessageBox.Show("List is null");
                            else
                            {
                                sb.Append("List: " + _ssrList.Title + " - Failed\n");
                                sb2.Append("\nList: " + _ssrList.Title + " - Exception Details:\n" + ex.ToString());
                            }
                        }
                    }
                    spWeb.AllowUnsafeUpdates = false;
                }
                spSite.AllowUnsafeUpdates = false;
            }

            rchTxtOuput.Text = sb.ToString();
            rchTxtOuput.Text += "\n\n\n" + sb2.ToString();
        }

        private void btnDisableWorkflow_Click(object sender, EventArgs e)
        {
            rchTxtOuput.Text = "";
            if (cmbWorkflow.SelectedItem.ToString().Equals("Select..."))
            {
                MessageBox.Show("Please make sure workflow is selected");
                return;
            }
            System.Globalization.CultureInfo _cultureInfo = System.Globalization.CultureInfo.CurrentCulture;
            SPWorkflowTemplate _wft;
            SPList _ssrList = null;
            SPList _taskList;
            SPList _wfHistoryList;
            SPWorkflowAssociation _newAsso;
            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            using (SPSite spSite = new SPSite(txtSiteUrl.Text))
            {
                spSite.AllowUnsafeUpdates = true;
                using (SPWeb spWeb = spSite.RootWeb)
                {
                    spWeb.AllowUnsafeUpdates = true;
                    foreach (object item in chxlbLists.CheckedItems)
                    {
                        try
                        {
                            //cmbWorkflow.Items.Add(item.ToString());
                            _ssrList = spWeb.Lists[item.ToString()];
                            _wft = spWeb.WorkflowTemplates.GetTemplateByName(cmbWorkflow.SelectedItem.ToString(), _cultureInfo);

                            foreach (SPWorkflowAssociation spwf in _ssrList.WorkflowAssociations)
                            {
                                if (spwf.Enabled && spwf.BaseTemplate.Id == _wft.Id)
                                {
                                    spwf.Enabled = false;
                                    _ssrList.UpdateWorkflowAssociation(spwf);
                                    break;
                                }
                            }

                            _ssrList.Update();
                            sb.Append("List: " + _ssrList.Title + " - Success\n");
                        }
                        catch (Exception ex)
                        {
                            if (_ssrList == null) MessageBox.Show("List is null");
                            else
                            {
                                sb.Append("List: " + _ssrList.Title + " - Failed\n");
                                sb2.Append("\nList: " + _ssrList.Title + " - Exception Details:\n" + ex.ToString());
                            }
                        }
                    }
                    spWeb.AllowUnsafeUpdates = false;
                }
                spSite.AllowUnsafeUpdates = false;
            }

            rchTxtOuput.Text = sb.ToString();
            rchTxtOuput.Text += "\n\n\n" + sb2.ToString();
        }

        private void txtAssocName_TextChanged(object sender, EventArgs e)
        {

        }
    }
}